package com.woniuxy.rabbitmq.sender;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: wanghao
 * @Date: 2019/9/11 15:21
 */
@Component(value = "firstSender")
public class FirstSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     * @param uuid
     * @param message  消息
     */
    public void send(String uuid,Object message,String exchange,String routingKey) {
        CorrelationData correlationId = new CorrelationData(uuid);
        rabbitTemplate.convertAndSend(exchange, routingKey, message, correlationId);
    }

    /**
     * 发送延迟信息
     * @param uuid
     * @param message
     * @param exchange
     * @param routingKey
     * @param time
     */
    public void sendDelayed(String uuid,Object message,String exchange,String routingKey,Long time) {
        CorrelationData correlationId = new CorrelationData(uuid);
            rabbitTemplate.convertAndSend(
                    exchange,
                    routingKey,
                    message,
                    new MessagePostProcessor() {
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            message.getMessageProperties().setHeader("x-delay",time);
                            return message;
                        }
                    },
                    correlationId
            );
        }
    }

